package com.unittec.drainage.provider.manage.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.unittec.drainage.provider.common.Md5;
import com.unittec.drainage.provider.manage.dto.WaterheadFeeCollectionDto;
import com.unittec.drainage.provider.manage.entity.WaterheadUser;
import com.unittec.drainage.provider.scope.ThreadLocalScope;
import com.unittec.drainage.provider.scope.ThreadLocalScopeCache;
import com.unittec.drainage.provider.service.HystrixRestTemplateService;
import com.unittec.drainage.provider.utils.CopyUtils;
import com.unittec.drainage.provider.utils.UUIDUtils;
import com.unittec.drainage.sdk.auth.domain.SysUserInfo;
import com.unittec.drainage.sdk.auth.request.Req101135;
import com.unittec.drainage.sdk.auth.response.Res101135;
import com.unittec.drainage.sdk.manage.request.*;
import com.unittec.drainage.sdk.root.common.FieldConstants;
import com.unittec.drainage.sdk.root.domain.GatewayRequest;
import com.unittec.drainage.sdk.root.domain.Result;
import com.unittec.drainage.sdk.root.internal.exception.BusinessException;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.SystemUtils;
import org.bouncycastle.cert.ocsp.Req;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.unittec.drainage.provider.manage.mapper.WaterheadFeeCollectionMapper;
import com.unittec.drainage.provider.manage.entity.WaterheadFeeCollection;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author Jason
 * @date 2021/8/11
 */
@Transactional
@Service
public class WaterheadFeeCollectionService extends ServiceImpl<WaterheadFeeCollectionMapper, WaterheadFeeCollection> {

    @Resource
    private UserService userService;

    @Resource
    private WaterheadUserService waterheadUserService;

    @Resource
    private WaterheadFeeCollectionMapper waterheadFeeCollectionMapper;

    @Resource
    private HystrixRestTemplateService hystrixRestTemplateService;

    /**
     * 污水费应收新增
     * @param req301106
     */
    public void addWaterheadReceivable(Req301106 req301106) {
        //应收月和应收日的月份应该一致
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM");
        String month = df.format(req301106.getReceivableMonth());
        String date = df.format(req301106.getReceivableDate());
        if(!month.equals(date)){
            throw new BusinessException("应收月和应收日应该是同一个月");
        }
        //判断对应的用户是否销户
        if("1".equals(waterheadUserService.getById(req301106.getWaterheadUserId()).getState())){
            throw new BusinessException("该用户状态异常，请重新选择用户");
        }
        WaterheadFeeCollection waterheadFeeCollection = new WaterheadFeeCollection();
        String id = UUIDUtils.getId();
        waterheadFeeCollection.setId(id);
        waterheadFeeCollection.setWaterheadType(req301106.getWaterheadType());
        waterheadFeeCollection.setWaterheadUserId(req301106.getWaterheadUserId());
        waterheadFeeCollection.setReceivableMonth(req301106.getReceivableMonth());
        waterheadFeeCollection.setReceivableDate(req301106.getReceivableDate());
        waterheadFeeCollection.setWaterConsumption(req301106.getWaterConsumption());
        waterheadFeeCollection.setWaterDischarge(req301106.getWaterDischarge());
        waterheadFeeCollection.setWaterPrice(req301106.getWaterPrice());
        waterheadFeeCollection.setWaterMoney(req301106.getWaterMoney());
        this.save(waterheadFeeCollection);
    }

    /**
     * 污水费应收编辑
     * @param req301107
     */
    public void updateWaterheadReceivable(Req301107 req301107) {
        //判断对应的用户是否销户
        if("1".equals(waterheadUserService.getById(req301107.getWaterheadUserId()))){
            throw new BusinessException("该用户状态异常，请重新选择用户");
        }
        //已收款的不能编辑
        if("1".equals(this.getById(req301107.getId()).getIsPay())){
            throw new BusinessException("该污水费已完成支付，无需编辑");
        }
        //应收月份和日应该在同一个月
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM");
        String month = df.format(req301107.getReceivableMonth());
        String date = df.format(req301107.getReceivableDate());
        if(!month.equals(date)){
            throw new BusinessException("应收月和应收日应该是同一个月");
        }
        WaterheadFeeCollection waterheadFeeCollection = new WaterheadFeeCollection();
        CopyUtils.copyProperties(req301107,waterheadFeeCollection);
        this.updateById(waterheadFeeCollection);
    }

    /**
     * 污水费应收删除
     * @param req301108
     */
    public void delWaterheadReceivable(Req301108 req301108) {
        //已付款的和冲正的不能删除
        LambdaQueryWrapper<WaterheadFeeCollection> lqw = new LambdaQueryWrapper<>();
        lqw.in(WaterheadFeeCollection::getId,req301108.getIds());
        List<WaterheadFeeCollection> list = this.list(lqw);
        for (WaterheadFeeCollection w : list) {
            if ("1".equals(w.getIsPay())){
                throw new BusinessException("已收费的记录不能删除,请于实收中点击冲正");
            }
        }
        this.removeByIds(req301108.getIds());
    }

    /**
     * 污水费应收导出
     * @param req301109
     * @return
     */
    public List<Map<String, Object>> getWaterheadReceivableList(Req301109 req301109) {
        LambdaQueryWrapper<?> qw = new LambdaQueryWrapper();
        //水源类型
        if(StringUtils.isNotBlank(req301109.getWaterheadType())){
            qw.apply("f.waterhead_type = '"+req301109.getWaterheadType()+"'");
        }
        //应收月开始时间
        if(req301109.getReceivableMonthStart()!=null){
            qw.apply("f.receivable_month >= '"+req301109.getReceivableMonthStart()+"'");
        }
        //应收月结束时间
        if(req301109.getReceivableMonthEnd()!=null){
            qw.apply("f.receivable_month <= '"+req301109.getReceivableMonthEnd()+"'");
        }
        //用户代码
        if(StringUtils.isNotBlank(req301109.getUserCode())){
            qw.apply("user_code like '%"+req301109.getUserCode()+"%'");
        }
        //用户名称
        if(StringUtils.isNotBlank(req301109.getUserName())){
            qw.apply("user_name like '%"+req301109.getUserName()+"%'");
        }
        //用户地址
        if(StringUtils.isNotBlank(req301109.getUserAddress())){
            qw.apply("user_address like '%"+req301109.getUserAddress()+"%'");
        }
        //联系电话
        if(StringUtils.isNotBlank(req301109.getUserPhone())){
            qw.apply("user_phone like '%"+req301109.getUserPhone()+"%'");
        }
        //缴费状态
        if(StringUtils.isNotBlank(req301109.getIsPay())){
            qw.apply("is_pay = '"+req301109.getIsPay()+"'");
        }
        //冲正的数据不需要
        qw.apply("is_righting = '0'");

        List<Map<String, Object>> list = waterheadFeeCollectionMapper.getWaterheadFeeCollectionPage(qw);
        //先将所有用户查出来，方便后面做查询和赋值
        List<SysUserInfo> userList = userService.getUserList(new GatewayRequest<Req101135>(), new Req101135());
        //给page填充name
        //将用户列表转为map方便查找
        HashMap<String, SysUserInfo> usersMap = new HashMap<>();
        for (SysUserInfo sysUserInfo : userList) {
            usersMap.put(sysUserInfo.getId(),sysUserInfo);
        }
        //给对应id填入对实收用户名
        for (Map<String, Object> record : list) {
            if (record.get("receipts_by")!=null && usersMap.get(record.get("receipts_by"))!=null){
                record.put("receipts_by",usersMap.get(record.get("receipts_by")).getRealname());
            }
            if (record.get("modify_user")!=null && usersMap.get(record.get("modify_user"))!=null){
                record.put("modify_user",usersMap.get(record.get("modify_user")).getRealname());
            }
        }
        return list;
    }

    /**
     * 污水费应收条件分页查询
     * @param req301110
     * @return
     */
    public Map<String, Object> getWaterheadReceivablePage(Req301110 req301110) {
        Page<?> page = new Page<>(req301110.getCurrent(), req301110.getSize());
        LambdaQueryWrapper<?> qw = new LambdaQueryWrapper();
        //水源类型
        if(StringUtils.isNotBlank(req301110.getWaterheadType())){
            qw.apply("f.waterhead_type = '"+req301110.getWaterheadType()+"'");
        }
        //应收月开始时间
        if(req301110.getReceivableMonthStart()!=null){
            qw.apply("f.receivable_month >= '"+req301110.getReceivableMonthStart()+"'");
        }
        //应收月结束时间
        if(req301110.getReceivableMonthEnd()!=null){
            qw.apply("f.receivable_month <= '"+req301110.getReceivableMonthEnd()+"'");
        }
        //用户代码
        if(StringUtils.isNotBlank(req301110.getUserCode())){
            qw.apply("user_code like '%"+req301110.getUserCode()+"%'");
        }
        //用户名称
        if(StringUtils.isNotBlank(req301110.getUserName())){
            qw.apply("user_name like '%"+req301110.getUserName()+"%'");
        }
        //用户地址
        if(StringUtils.isNotBlank(req301110.getUserAddress())){
            qw.apply("user_address like '%"+req301110.getUserAddress()+"%'");
        }
        //联系电话
        if(StringUtils.isNotBlank(req301110.getUserPhone())){
            qw.apply("user_phone like '%"+req301110.getUserPhone()+"%'");
        }
        //缴费状态
        if(StringUtils.isNotBlank(req301110.getIsPay())){
            qw.apply("is_pay = '"+req301110.getIsPay()+"'");
        }
        //冲正的数据不需要
        qw.apply("is_righting = '0'");

        IPage<Map<String, Object>> iPage = waterheadFeeCollectionMapper.getWaterheadFeeCollectionPage(page, qw);
        //先将所有用户查出来，方便后面做查询和赋值
        List<SysUserInfo> userList = userService.getUserList(new GatewayRequest<Req101135>(), new Req101135());
        //给page填充name
        //将用户列表转为map方便查找
        HashMap<String, SysUserInfo> usersMap = new HashMap<>();
        for (SysUserInfo sysUserInfo : userList) {
            usersMap.put(sysUserInfo.getId(),sysUserInfo);
        }
        //给对应id填入对实收用户名
        List<Map<String, Object>> records = iPage.getRecords();
        for (Map<String, Object> record : records) {
            if (record.get("receipts_by")!=null && usersMap.get(record.get("receipts_by"))!=null){
                record.put("receipts_by",usersMap.get(record.get("receipts_by")).getRealname());
            }
            if (record.get("modify_user")!=null && usersMap.get(record.get("modify_user"))!=null){
                record.put("modify_user",usersMap.get(record.get("modify_user")).getRealname());
            }
        }

        Map<String, Object> total = waterheadFeeCollectionMapper.getWaterheadFeeCollectionTotal(qw);
        HashMap<String, Object> all = new HashMap<>();
        all.put("page",iPage);
        all.put("total",total);
        return all;
    }

    /**
     * 污水费详情
     * @param req301123
     * @return
     */
    public Object getWaterheadFeeCollectionProInfo(Req301123 req301123) {
        WaterheadFeeCollection waterheadFeeCollection = this.getById(req301123.getId());
        WaterheadFeeCollectionDto waterheadFeeCollectionDto = new WaterheadFeeCollectionDto();
        if(waterheadFeeCollection != null){
            CopyUtils.copyProperties(waterheadFeeCollection, waterheadFeeCollectionDto);
            WaterheadUser waterheadUser = waterheadUserService.getById(waterheadFeeCollectionDto.getWaterheadUserId());
            waterheadFeeCollectionDto.setUserCode(waterheadUser.getUserCode());
            waterheadFeeCollectionDto.setUserName(waterheadUser.getUserName());
            waterheadFeeCollectionDto.setUserAddress(waterheadUser.getUserAddress());
            waterheadFeeCollectionDto.setUserPhone(waterheadUser.getUserPhone());
            waterheadFeeCollectionDto.setLevyMode(waterheadUser.getLevyMode());
            waterheadFeeCollectionDto.setWaterNature(waterheadUser.getWaterNature());
            waterheadFeeCollectionDto.setPriceCategory(waterheadUser.getPriceCategory());
            waterheadFeeCollectionDto.setLevyStandard(waterheadUser.getLevyStandard());
        }else {
            return null;
        }
        Req101135 req101135 = new Req101135();
        List<String> strings = queryCustomerStaffUserListById(new GatewayRequest<Req101135>(),req101135);
        return waterheadFeeCollectionDto;
    }

    /**
     * 根据员工id查询员工id列表
     * @param req
     * @param req101135
     * * @return
     */
    public List<String> queryCustomerStaffUserListById(GatewayRequest<Req101135> req, Req101135 req101135) {
        req.setMethod("101135");
        req.setContent(req101135);
        Result<Res101135> result = hystrixRestTemplateService.exchange(Md5.getMd5(FieldConstants.SYS_REQUEST_SOURCE_ID),
                "http://drainage-auth-101/101135", req, ThreadLocalScope.getAuthData(),
                        new ParameterizedTypeReference<Result<Res101135>>(){});
        if (result.isSuccess()) {
            return result.getData().getList().stream().map(sysUserRes -> sysUserRes.getId())
                    .collect(Collectors.toList());
        }
        throw new BusinessException(result.getBizMsg());
    }

    /**
     * 污水费实收收款
     * @param req301111
     */
    public void makeWaterheadFeeCollection(Req301111 req301111) {
        WaterheadFeeCollection waterheadFeeCollection = this.getById(req301111.getId());
        if("1".equals(waterheadFeeCollection.getIsRighting())){
            throw new BusinessException("该记录为冲正数据，无需收款");
        }
        if("1".equals(waterheadFeeCollection.getIsPay())){
            throw new BusinessException("该记录已经收款，无需再次收款，如果该记录录入错误，请点击冲正后重新收款");
        }
        if(req301111.getReceivableWaterMoney().compareTo(req301111.getReceiptsWaterMoney())!=0){
            throw new BusinessException("实收金额应等于应收金额");
        }
        waterheadFeeCollection.setReceivableWaterMoney(req301111.getReceivableWaterMoney());
        waterheadFeeCollection.setReceiptsWaterMoney(req301111.getReceivableWaterMoney());
        //实收日期
        String l = String.valueOf(System.currentTimeMillis());
        waterheadFeeCollection.setReceiptsDate(new Date(Long.valueOf(l.substring(0,l.length()-3)+"000")));
        //实收人员id
        ThreadLocalScope.AuthData authData = ThreadLocalScope.getAuthData();
        waterheadFeeCollection.setReceiptsBy(authData.getUser());
        //修改支付状态为已支付
        waterheadFeeCollection.setIsPay("1");
        this.updateById(waterheadFeeCollection);
    }

    /**
     * 污水费实收冲正
     * @param req301112
     */
    public void rightingWaterheadFeeCollection(Req301112 req301112) {
        //判断
        WaterheadFeeCollection byId = this.getById(req301112.getId());
        if("0".equals(byId.getIsPay())){
            throw new BusinessException("该记录未完成收款，无需冲正");
        }
        if("1".equals(byId.getIsRighting())){
            throw new BusinessException("该记录为已冲正数据，无需重复冲正");
        }
        //修改原纪录为已冲正
        byId.setIsRighting("1");
        byId.setModifyUser(ThreadLocalScope.getAuthData().getUser());
        this.updateById(byId);
        //新增一条纪录，实收为负，已冲正
        byId.setReceiptsWaterMoney(byId.getReceiptsWaterMoney().negate());
        byId.setId(UUIDUtils.getId());
        this.save(byId);
        //新增一条相同但未收款的记录
        WaterheadFeeCollection waterheadFeeCollection = new WaterheadFeeCollection();
        waterheadFeeCollection.setId(UUIDUtils.getId());
        waterheadFeeCollection.setWaterheadType(byId.getWaterheadType());
        waterheadFeeCollection.setWaterheadUserId(byId.getWaterheadUserId());
        waterheadFeeCollection.setReceivableMonth(byId.getReceivableMonth());
        waterheadFeeCollection.setReceivableDate(byId.getReceivableDate());
        waterheadFeeCollection.setWaterConsumption(byId.getWaterConsumption());
        waterheadFeeCollection.setWaterDischarge(byId.getWaterDischarge());
        waterheadFeeCollection.setWaterPrice(byId.getWaterPrice());
        waterheadFeeCollection.setWaterMoney(byId.getWaterMoney());
        waterheadFeeCollection.setCreateTime(byId.getCreateTime());
        waterheadFeeCollection.setCreateUser(byId.getCreateUser());
        this.save(waterheadFeeCollection);
    }

    /**
     * 污水费应收导出
     * @param req301113
     * @return
     */
    public List<Map<String, Object>> getWaterheadReceipstList(Req301113 req301113) {
        //条件
        LambdaQueryWrapper<?> qw = new LambdaQueryWrapper();
        //水源类型
        if(StringUtils.isNotBlank(req301113.getWaterheadType())){
            qw.apply("a.waterhead_type = '"+req301113.getWaterheadType()+"'");
        }
        //应收月开始时间
        if(req301113.getReceivableMonthStart()!=null){
            qw.apply("a.receivable_month >= '"+req301113.getReceivableMonthStart()+"'");
        }
        //应收月结束时间
        if(req301113.getReceivableMonthEnd()!=null){
            qw.apply("a.receivable_month <= '"+req301113.getReceivableMonthEnd()+"'");
        }
        //用户代码
        if(StringUtils.isNotBlank(req301113.getUserCode())){
            qw.apply("b.user_code like '%"+req301113.getUserCode()+"%'");
        }
        //用户名称
        if(StringUtils.isNotBlank(req301113.getUserName())){
            qw.apply("b.user_name like '%"+req301113.getUserName()+"%'");
        }
        //征收方式
        if(StringUtils.isNotBlank(req301113.getLevyMode())){
            qw.apply("b.levy_mode = '"+req301113.getLevyMode()+"'");
        }
        //污水价类别
        if(StringUtils.isNotBlank(req301113.getPriceCategory())){
            qw.apply("b.price_category = '"+req301113.getPriceCategory()+"'");
        }
        //先将所有用户查出来，方便后面做查询和赋值
        List<SysUserInfo> userList = userService.getUserList(new GatewayRequest<Req101135>(), new Req101135());

        //收费人员
        if(StringUtils.isNotBlank(req301113.getReceiptsName())){
            //在集合中找到对应名字的id，可能重名，所以一个名字可能对应多个id
            StringBuilder ids = new StringBuilder();
            for (SysUserInfo sysUserInfo : userList) {
                if(sysUserInfo.getRealname().indexOf(req301113.getReceiptsName()) != -1){
                    ids.append("'"+sysUserInfo.getId()+"'");
                    ids.append(',');
                }
            }
            qw.apply(ids.length() > 0 ? "a.receipts_by in (" + ids.substring(0, ids.length() - 1) + ")" : "a.receipts_by in ('')");
        }
        List<Map<String, Object>> list = this.baseMapper.getWaterheadFeeCollectionReceiptsPage(qw);

        //给page填充name
        //将用户列表转为map方便查找
        HashMap<String, SysUserInfo> usersMap = new HashMap<>();
        for (SysUserInfo sysUserInfo : userList) {
            usersMap.put(sysUserInfo.getId(),sysUserInfo);
        }
        //给对应id填入对实收用户名
        for (Map<String, Object> record : list) {
            if (record.get("receipts_by")!=null && usersMap.get(record.get("receipts_by"))!=null){
                record.put("receipts_name",usersMap.get(record.get("receipts_by")).getRealname());
            }
            if (record.get("modify_user")!=null && usersMap.get(record.get("modify_user"))!=null){
                record.put("modify_user",usersMap.get(record.get("modify_user")).getRealname());
            }
        }
        return list;
    }

    /**
     * 污水费实收条件分页查询
     * @param req301114
     * @return
     */
    public Object getWaterheadFeeCollectionReceipstPage(Req301114 req301114) {
        //条件
        LambdaQueryWrapper<?> qw = new LambdaQueryWrapper();
        //水源类型
        if(StringUtils.isNotBlank(req301114.getWaterheadType())){
            qw.apply("a.waterhead_type = '"+req301114.getWaterheadType()+"'");
        }
        //应收月开始时间
        if(req301114.getReceivableMonthStart()!=null){
            qw.apply("a.receivable_month >= '"+req301114.getReceivableMonthStart()+"'");
        }
        //应收月结束时间
        if(req301114.getReceivableMonthEnd()!=null){
            qw.apply("a.receivable_month <= '"+req301114.getReceivableMonthEnd()+"'");
        }
        //用户代码
        if(StringUtils.isNotBlank(req301114.getUserCode())){
            qw.apply("b.user_code like '%"+req301114.getUserCode()+"%'");
        }
        //用户名称
        if(StringUtils.isNotBlank(req301114.getUserName())){
            qw.apply("b.user_name like '%"+req301114.getUserName()+"%'");
        }
        //征收方式
        if(StringUtils.isNotBlank(req301114.getLevyMode())){
            qw.apply("b.levy_mode = '"+req301114.getLevyMode()+"'");
        }
        //污水价类别
        if(StringUtils.isNotBlank(req301114.getPriceCategory())){
            qw.apply("b.price_category = '"+req301114.getPriceCategory()+"'");
        }
        //先将所有用户查出来，方便后面做查询和赋值
        List<SysUserInfo> userList = userService.getUserList(new GatewayRequest<Req101135>(), new Req101135());

        //收费人员
        if(StringUtils.isNotBlank(req301114.getReceiptsName())){
            //在集合中找到对应名字的id，可能重名，所以一个名字可能对应多个id
            StringBuilder ids = new StringBuilder();
            for (SysUserInfo sysUserInfo : userList) {
                if(sysUserInfo.getRealname().indexOf(req301114.getReceiptsName()) != -1){
                    ids.append("'"+sysUserInfo.getId()+"'");
                    ids.append(',');
                }
            }
            qw.apply(ids.length() > 0 ? "a.receipts_by in (" + ids.substring(0, ids.length() - 1) + ")" : "a.receipts_by in ('')");
        }
        //page
        Page<Object> page = new Page<>(req301114.getCurrent(), req301114.getSize());
        IPage<Map<String, Object>> iPage = this.baseMapper.getWaterheadFeeCollectionReceiptsPage(page, qw);

        //给page填充name
        //将用户列表转为map方便查找
        HashMap<String, SysUserInfo> usersMap = new HashMap<>();
        for (SysUserInfo sysUserInfo : userList) {
            usersMap.put(sysUserInfo.getId(),sysUserInfo);
        }
        //给对应id填入对实收用户名
        List<Map<String, Object>> records = iPage.getRecords();
        for (Map<String, Object> record : records) {
            if (record.get("receipts_by")!=null && usersMap.get(record.get("receipts_by"))!=null){
                record.put("receipts_name",usersMap.get(record.get("receipts_by")).getRealname());
            }
            if (record.get("modify_user")!=null && usersMap.get(record.get("modify_user"))!=null){
                record.put("modify_user",usersMap.get(record.get("modify_user")).getRealname());
            }
        }
        //统计
        //不统计冲正数据
        qw.apply("is_righting = '0'");
        Map<String, Object> total = this.baseMapper.getWaterheadFeeCollectionReceiptsTotal(qw);
        HashMap<String, Object> all = new HashMap<>();
        all.put("page",iPage);
        all.put("total",total);
        return all;
    }

    /**
     * 污水费欠收条件分页查询
     * @param req301116
     * @return
     */
    public Object getWaterheadFeeCollectionArrearsPage(Req301116 req301116) {
        //条件
        LambdaQueryWrapper<WaterheadFeeCollection> lqw = new LambdaQueryWrapper<>();
        //水源类型
        if(StringUtils.isNotBlank(req301116.getWaterheadType())){
            lqw.apply("a.waterhead_type = '"+req301116.getWaterheadType()+"'");
        }
        //应收月开始时间
        if(req301116.getReceivableMonthStart()!=null){
            lqw.apply("a.receivable_month >= '"+req301116.getReceivableMonthStart()+"'");
        }
        //应收月结束时间
        if(req301116.getReceivableMonthEnd()!=null){
            lqw.apply("a.receivable_month <= '"+req301116.getReceivableMonthEnd()+"'");
        }
        //用户代码
        if(StringUtils.isNotBlank(req301116.getUserCode())){
            lqw.apply("b.user_code like '%"+req301116.getUserCode()+"%'");
        }
        //用户名称
        if(StringUtils.isNotBlank(req301116.getUserName())){
            lqw.apply("b.user_name like '%"+req301116.getUserName()+"%'");
        }
        //征收方式
        if(StringUtils.isNotBlank(req301116.getLevyMode())){
            lqw.apply("b.levy_mode like '%"+req301116.getLevyMode()+"%'");
        }
        //污水价类别
        if(StringUtils.isNotBlank(req301116.getPriceCategory())){
            lqw.apply("b.price_category = '"+req301116.getPriceCategory()+"'");
        }
        //先将所有用户查出来，方便后面做查询和赋值
        List<SysUserInfo> userList = userService.getUserList(new GatewayRequest<Req101135>(), new Req101135());
        //录入人员（根据名字模糊查询）
        if(StringUtils.isNotBlank(req301116.getCreateUserName())){
            //在集合中找到对应名字的id，可能重名，所以一个名字可能对应多个id
            StringBuilder ids = new StringBuilder();
            for (SysUserInfo sysUserInfo : userList) {
                if(sysUserInfo.getRealname().indexOf(req301116.getCreateUserName()) != -1){
                    ids.append("'"+sysUserInfo.getId()+"'");
                    ids.append(',');
                }
            }
            lqw.apply(ids.length() > 0 ? "a.create_user in (" + ids.substring(0, ids.length() - 1) + ")" : "a.create_user in ('')");
        }
        //到期未支付的
        lqw.eq(WaterheadFeeCollection::getIsPay,'0');
        lqw.lt(WaterheadFeeCollection::getReceivableDate,new Date(System.currentTimeMillis()));
        //查询数据库
        IPage<Map<String, Object>> iPage = this.baseMapper.getWaterheadFeeCollectionArrearsPage(new Page<>(req301116.getCurrent(), req301116.getSize()), lqw);
        //将用户列表转为map方便查找
        HashMap<String, SysUserInfo> usersMap = new HashMap<>();
        for (SysUserInfo sysUserInfo : userList) {
            usersMap.put(sysUserInfo.getId(),sysUserInfo);
        }
        //给对应id填入对应用户名
        List<Map<String, Object>> records = iPage.getRecords();
        for (Map<String, Object> record : records) {
            try {
                String create_user = usersMap.get(record.get("create_user")).getRealname();
                record.put("create_user",create_user);
            }catch (Exception e){
                record.put("create_user","该账号已删除");
            }
        }
        Map<String, Object> total = this.baseMapper.getWaterheadFeeCollectionArrearsTotal(lqw);
        HashMap<String, Object> object = new HashMap<>();
        object.put("page",iPage);
        object.put("total",total);
        return object;
    }

    /**
     * 欠收导出
     * @param req301117
     * @return
     */
    public List<Map<String, Object>> getWaterheadArrearsList(Req301117 req301117) {
        //条件
        LambdaQueryWrapper<WaterheadFeeCollection> lqw = new LambdaQueryWrapper<>();
        //水源类型
        if(StringUtils.isNotBlank(req301117.getWaterheadType())){
            lqw.apply("a.waterhead_type = '"+req301117.getWaterheadType()+"'");
        }
        //应收月开始时间
        if(req301117.getReceivableMonthStart()!=null){
            lqw.apply("a.receivable_month >= '"+req301117.getReceivableMonthStart()+"'");
        }
        //应收月结束时间
        if(req301117.getReceivableMonthEnd()!=null){
            lqw.apply("a.receivable_month <= '"+req301117.getReceivableMonthEnd()+"'");
        }
        //用户代码
        if(StringUtils.isNotBlank(req301117.getUserCode())){
            lqw.apply("b.user_code like '%"+req301117.getUserCode()+"%'");
        }
        //用户名称
        if(StringUtils.isNotBlank(req301117.getUserName())){
            lqw.apply("b.user_name like '%"+req301117.getUserName()+"%'");
        }
        //征收方式
        if(StringUtils.isNotBlank(req301117.getLevyMode())){
            lqw.apply("b.levy_mode like '%"+req301117.getLevyMode()+"%'");
        }
        //污水价类别
        if(StringUtils.isNotBlank(req301117.getPriceCategory())){
            lqw.apply("b.price_category = '"+req301117.getPriceCategory()+"'");
        }
        //先将所有用户查出来，方便后面做查询和赋值
        List<SysUserInfo> userList = userService.getUserList(new GatewayRequest<Req101135>(), new Req101135());
        //录入人员（根据名字模糊查询）
        if(StringUtils.isNotBlank(req301117.getCreateUserName())){
            //在集合中找到对应名字的id，可能重名，所以一个名字可能对应多个id
            StringBuilder ids = new StringBuilder();
            for (SysUserInfo sysUserInfo : userList) {
                if(sysUserInfo.getRealname().indexOf(req301117.getCreateUserName()) != -1){
                    ids.append("'"+sysUserInfo.getId()+"'");
                    ids.append(',');
                }
            }
            lqw.apply(ids.length() > 0 ? "a.create_user in (" + ids.substring(0, ids.length() - 1) + ")" : "a.create_user in ('')");
        }
        //到期未支付的
        lqw.eq(WaterheadFeeCollection::getIsPay,'0');
        lqw.lt(WaterheadFeeCollection::getReceivableDate,new Date(System.currentTimeMillis()));
        //查询数据库
        List<Map<String, Object>> list = this.baseMapper.getWaterheadFeeCollectionArrearsPage(lqw);
        //将用户列表转为map方便查找
        HashMap<String, SysUserInfo> usersMap = new HashMap<>();
        for (SysUserInfo sysUserInfo : userList) {
            usersMap.put(sysUserInfo.getId(),sysUserInfo);
        }
        //给对应id填入对应用户名
        for (Map<String, Object> record : list) {
            try {
                String create_user = usersMap.get(record.get("create_user")).getRealname();
                record.put("create_user",create_user);
            }catch (Exception e){
                record.put("create_user","该账号已删除");
            }
        }
        return list;
    }
    /**
     * 月度统计报表
     * @param req301118
     * @return
     */
    public Object monthlyReport(Req301118 req301118) {
        LambdaQueryWrapper<?> lqw = new LambdaQueryWrapper<>();
        //条件
        //年份
        if(null != req301118.getYear()){
            lqw.apply("to_char(receivable_date,'YYYY')='"+new SimpleDateFormat("yyyy").format(req301118.getYear())+"'");
        }
        //水源类型
        if(StringUtils.isNotBlank(req301118.getWaterheadType())){
            lqw.apply("waterhead_type = '"+req301118.getWaterheadType()+"'");
        }
        //不统计冲正数据
        lqw.apply("is_righting = '0'");
        IPage<Map<String, Object>> iPage = this.baseMapper.getMonthlyReportPage(new Page<>(req301118.getCurrent(), req301118.getSize()), lqw);
        //总计
        Map<String, Object> total = this.baseMapper.getMonthlyReportTotal(lqw);
        HashMap<String, Object> object = new HashMap<>();
        object.put("page",iPage);
        object.put("total",total);
        return object;
    }

    /**
     * 月度报表导出
     * @param req301125
     * @return
     */
    public List<Map<String, Object>> getMonthlyReportList(Req301125 req301125) {
        LambdaQueryWrapper<?> lqw = new LambdaQueryWrapper<>();
        //条件
        //年份
        if(null != req301125.getYear()){
            lqw.apply("to_char(receivable_date,'YYYY')='"+new SimpleDateFormat("yyyy").format(req301125.getYear())+"'");
        }
        //水源类型
        if(StringUtils.isNotBlank(req301125.getWaterheadType())){
            lqw.apply("waterhead_type = '"+req301125.getWaterheadType()+"'");
        }
        //不统计冲正数据
        lqw.apply("is_righting = '0'");
        List<Map<String, Object>> list = this.baseMapper.getMonthlyReportPage(lqw);
        return list;
    }

    /**
     * 年度统计报表
     * @param req301119
     * @return
     */
    public Object yearlyReport(Req301119 req301119) {
        LambdaQueryWrapper<?> lqw = new LambdaQueryWrapper<>();
        //条件
        //水源类型
        if (StringUtils.isNotBlank(req301119.getWaterheadType())) {
            lqw.apply("waterhead_type = '" + req301119.getWaterheadType() + "'");
        }
        //年份开始
        if (null != req301119.getYearStart()) {
            lqw.apply("receivable_date >= '" + req301119.getYearStart() + "'");
        }
        //年份结束
        if (null != req301119.getYearEnd()) {
            Calendar cd = Calendar.getInstance();
            cd.setTime(req301119.getYearEnd());
            cd.add(Calendar.YEAR,1);
            Date time = cd.getTime();
            lqw.apply("receivable_date <= '" + time + "'");
        }
        //不统计冲正数据
        lqw.apply("is_righting = '0'");
        IPage<Map<String, Object>> iPage = this.baseMapper.getYearlyReportPage(new Page<>(req301119.getCurrent(), req301119.getSize()), lqw);
        Map<String, Object> total = this.baseMapper.getYearlyReportTotal(lqw);
        HashMap<String, Object> object = new HashMap<>();
        object.put("page",iPage);
        object.put("total",total);
        return object;
    }

    /**
     * 年度报表统计导出
     * @param req301126
     * @return
     */
    public List<Map<String, Object>> getMonthlyReportList(Req301126 req301126) {
        LambdaQueryWrapper<?> lqw = new LambdaQueryWrapper<>();
        //条件
        //水源类型
        if (StringUtils.isNotBlank(req301126.getWaterheadType())) {
            lqw.apply("waterhead_type = '" + req301126.getWaterheadType() + "'");
        }
        //年份开始
        if (null != req301126.getYearStart()) {
            lqw.apply("receivable_date >= '" + req301126.getYearStart() + "'");
        }
        //年份结束
        if (null != req301126.getYearEnd()) {
            Calendar cd = Calendar.getInstance();
            cd.setTime(req301126.getYearEnd());
            cd.add(Calendar.YEAR,1);
            Date time = cd.getTime();
            lqw.apply("receivable_date <= '" + time + "'");
        }
        //不统计冲正数据
        lqw.apply("is_righting = '0'");
        List<Map<String, Object>> list = this.baseMapper.getYearlyReportPage(lqw);
        return list;
    }
}
